// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/login_page.dart';
import 'package:encrypt_and_decrypt_files/my/register_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class ResetPasswordPage extends StatefulWidget {
  const ResetPasswordPage({
    super.key,
  });

  @override
  State<ResetPasswordPage> createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController oldPasswordController = TextEditingController();
  final TextEditingController newPasswordController = TextEditingController();
  final TextEditingController secondPasswordController =
      TextEditingController();

  List<UserModel> allAccount = [];

  @override
  void dispose() {
    userNameController.dispose();
    oldPasswordController.dispose();
    newPasswordController.dispose();
    secondPasswordController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeProvider.mainColor,
        centerTitle: true,
        title: Text('Reset Password'.t(context)),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'Reset Password'.t(context),
                      style: const TextStyle(
                          fontSize: 18, fontWeight: FontWeight.bold),
                    )
                  ],
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: userNameController,
                  decoration: InputDecoration(
                    labelText: 'username:',
                    hintText: 'Please input username',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 16,
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: oldPasswordController,
                  decoration: InputDecoration(
                    labelText: 'oldPassword:',
                    hintText: 'Please input old password',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 16,
                    ),
                    suffixIcon: const Icon(Icons.lock),
                  ),
                  obscureText: true,
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: newPasswordController,
                  decoration: InputDecoration(
                    labelText: 'new password:',
                    hintText: 'Please input the new password',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 16,
                    ),
                    suffixIcon: const Icon(Icons.check, color: Colors.green),
                  ),
                  obscureText: true,
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: secondPasswordController,
                  decoration: InputDecoration(
                    labelText: 'Repeat new password:',
                    hintText: 'Please re-enter the password to confirm',
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 16,
                    ),
                    suffixIcon: newPasswordController.text ==
                            secondPasswordController.text
                        ? const Icon(Icons.check, color: Colors.green)
                        : const Icon(Icons.close, color: Colors.red),
                  ),
                  obscureText: true,
                ),
                const SizedBox(height: 20),
                Container(
                  decoration: BoxDecoration(
                    color: themeProvider.mainColor,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: resetPassword,
                          child: Text(
                            'Reset Password'.t(context),
                            style: const TextStyle(color: Colors.black),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 30),
                Container(
                  decoration: BoxDecoration(
                    color: themeProvider.mainColor,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextButton(
                          onPressed: () {
                            showDialog(
                              context: context,
                              builder: (BuildContext context) {
                                return AlertDialog(
                                  title: Text('Delete Account'.t(context)),
                                  content:  Text(
                                    'Your membership will not be refund.\n\nYou may use the same email to register new account once deleted.'.t(context),
                                    textAlign: TextAlign.center,
                                  ),
                                  actions: <Widget>[
                                    TextButton(
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                      child: Text('Cancel'.t(context)),
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        deleteAccount();
                                      },
                                      child: Text('Confirm'.t(context)),
                                    ),
                                  ],
                                );
                              },
                            );
                          },
                          child: Text(
                            'Delete Account'.t(context),
                            style: const TextStyle(color: Colors.black),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future<void> resetPassword() async {
    const url = '/update_password';
    String token = SpUtil.getString('token') ?? '';

    if (userNameController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your email');
      return;
    }
    if (oldPasswordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your old password');
      return;
    }
    if (newPasswordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your new password');
      return;
    }
    if (secondPasswordController.text.isEmpty) {
      Fluttertoast.showToast(msg: 'Please enter your new password again');
      return;
    }
    if(secondPasswordController.text != newPasswordController.text){
      Fluttertoast.showToast(msg: 'The two passwords do not match');
      return;
    }

    var params = {
      'password': newPasswordController.text,
    };
    var response = await DioHttp.of(context).put(url, params, token);
    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      SpUtil.remove('token');
      SpUtil.remove('userModel');
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const LoginPage()),
          (Route<dynamic> route) => false);
    }
  }

  Future<void> deleteAccount() async {
    String token = SpUtil.getString('token') ?? '';

    const url = '/delete_account';
    Map<String, dynamic> params = {};
    var response = await DioHttp.of(context).post(url, params, token);

    var resString = json.decode(response.toString());
    Navigator.of(context).pop();
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      SpUtil.remove('token');
      SpUtil.remove('userName');
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const LoginPage()),
          (Route<dynamic> route) => false);
    }
  }
}
